package com.own.component.common.util.encrypt.util;

import com.own.component.common.util.encrypt.BaseEncryptUtil;
import com.own.component.common.util.encrypt.model.CustomEncryptKey;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * HmacSha256Util
 *
 * @author chenxueli
 * @date 2021/3/27 19:11
 */
public class HmacSha256Util implements BaseEncryptUtil {

    /**
     * 公钥加密
     *
     * @param content          加密内容
     * @param customEncryptKey 秘钥
     * @return 加密后的内容
     */
    @Override
    public String encrypt(String content, CustomEncryptKey customEncryptKey) {
        try {
            var mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(content.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            var signData = mac.doFinal(customEncryptKey.getSecret().getBytes(StandardCharsets.UTF_8));
            return Base64.encodeBase64String(signData);
        } catch (Exception e) {
            return "";
        }
    }

}
